/**
 * Created by wukong on 2018/5/28.
 */

import moment from 'moment';
import utils from './utils';

export default {
  install (Vue) {
    Vue.prototype.utils = utils;
    Vue.filter('currency', (value, currency, decimals) => {
      const digitsRE = /(\d{3})(?=\d)/g;
      value = parseFloat(value);
      if (!isFinite(value) || (!value && value !== 0)) return '';
      currency = currency != null ? currency : '¥';
      decimals = decimals != null ? decimals : 2;
      const stringified = Math.abs(value).toFixed(decimals);
      const _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
      const i = _int.length % 3;
      const head = i > 0 ? (_int.slice(0, i) + (_int.length > 3 ? ',' : '')) : '';
      const _float = decimals ? stringified.slice(-1 - decimals) : '';
      const sign = value < 0 ? '-' : '';
      return sign + currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float;
      // value = parseInt(value * 100) / 100;
      // value = parseFloat(value);
      // if (value !== undefined && value !== null) {
      //   value = accMath.accDiv(accMath.accMul(parseFloat(value).toFixed(2), 100), 100);
      // }
      // if (symbol === '%') {
      //   return value + symbol;
      // }
      // return symbol + value;
    });
    Vue.filter('ratio', (value) => {
      if (value === null) {
        return `${0}%`;
      }
      return `${parseFloat(parseInt((value * 10000).toFixed(4), 10) / 100)}%`;
    });
    Vue.filter('dateFmt', (value = '', format = 'YYYY-MM-DD HH:mm:ss') => {
      if (value !== '') {
        return moment(value).format(format);
      }
      return '';
    });
    Vue.filter('ossStyle', (value, size = '640') => {
      const mkCDN = /mk-gc-img.maike51.com/;
      const aliCDN = /aliyuncs.com/;
      if (mkCDN.test(value) || aliCDN.test(value)) {
        if (size === '320') {
          value += '?x-oss-process=image/resize,w_320/quality,q_85';
        } else if (size === '160') {
          value += '?x-oss-process=image/resize,w_160/quality,q_85';
        } else if (size === '128') {
          value += '?x-oss-process=image/resize,w_128/quality,q_85';
        } else {
          value += '?x-oss-process=image/resize,w_640/quality,q_85';
        }
      }
      return value;
    });
    // 超过999显示999+，flag默认为空，当是金额时可以设为¥
    Vue.filter('numLimit', (value, maxValue = 999, flag = '') => {
      if (flag === undefined) {
        flag = '';
      }
      if (value > maxValue) {
        return `${flag + maxValue}+`;
      }
      return isNaN(value) ? flag + 0 : flag + parseFloat(value);
    });
  }
};
